package linc.spring.demo.conversion;

import linc.spring.demo.bean.Role;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

import java.util.Collections;
import java.util.Random;
import java.util.Set;

/**
 * @author yqlin
 * @date 2021/9/7 01:15
 * @description
 */
public class StringToRoleConverter implements ConditionalGenericConverter {
    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return sourceType.getType().equals(String.class) && targetType.getType().equals(Role.class);
    }


    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, Role.class));
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        Role role = new Role();
        role.setId(new Random().nextLong());
        role.setName(String.valueOf(source));
        return role;
    }
}
